<?php

namespace App\Exceptions;

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
use Illuminate\Routing\Exceptions\InvalidSignatureException;
use Illuminate\Validation\UnauthorizedException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Validation\ValidationException::class,
        \Tymon\JWTAuth\Exceptions\TokenBlacklistedException::class,
        \Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    public function render($request, Throwable $exception)
    {
        if (method_exists($exception, 'getStatusCode')) {
            $status_code = $exception->getStatusCode();
        } else {
            $status_code = $exception->getCode() ?: 500;
        }
        static $prev_response;
        $response = [];
        if ($exception instanceof MethodNotAllowedHttpException) {
            $response = [
                'code' => 403,
                'data' => null,
                'message' => '接口禁止访问',
                'error' => $exception->getMessage(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        } elseif ($exception instanceof ValidationException) {
            $response = [
                'code' => $status_code ?: 500,
                'data' => null,
                'message' => head($exception->errors())[0],
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        } elseif ($exception instanceof ModelNotFoundException) {
            $response = [
                'code' => $status_code ?: 500,
                'data' => null,
                'message' => '查询结果为空',
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        } elseif ($exception instanceof NotFoundHttpException) {
            $innerException = $exception->getPrevious();
            $response = [
                'code' => $status_code ?: 404,
                'data' => null,
                'message' => '访问地址无效',
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
            $prev_response = $response;
            if ($innerException instanceof ModelNotFoundException) {
                return $this->render($request, $innerException);
            }
        } elseif ($exception instanceof InvalidSignatureException) {
            $response = [
                'code' => $status_code ?: 500,
                'data' => null,
                'message' => '签名无效',
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        } elseif ($exception instanceof AuthorizationException || $exception instanceof UnauthorizedException) {
            $response = [
                'code' => $status_code ?: 402,
                'data' => null,
                'message' => '无权访问接口',
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        } elseif ($exception instanceof MaintenanceModeException) {
            $response = [
                'code' => $status_code ?: 500,
                'data' => null,
                'message' => '系统正在维护中……',
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        } else {
            if ($exception->getMessage() === 'Call to a member function requestIsConditional() on null') {
                if ($prev_response) {
                    return response()->json($prev_response);
                }
            }
            $response = [
                'code' => $status_code ?: 500,
                'data' => null,
                'message' => $exception->getMessage(),
                'error' => $exception->getTraceAsString(),
                'file' => $exception->getFile(). ':'. $exception->getLine()
            ];
        }
        if (!app()->has('cache')) {
            // CacheServiceProvider是延时加载，当有其他Provider在初始化时出异常
            // 在sessio driver为redis的时候，则获取cache会失败，导致页面空白，添加如下方式解决此问题
            config(['session.driver' => 'file']);
        }
        return response()->json($response);
    }
}
